package com.hbu.fleastreet.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hbu.fleastreet.entity.User;
import com.hbu.fleastreet.services.IUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * 权限拦截器,用于某些页面必须登陆以后才可以查看
 **/
@WebFilter
@Configuration
public class AuthorizationFilter implements Filter {
	private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationFilter.class);
	@Autowired
	private IUserService userService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		// 支持跨域访问
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers",
				"Origin, X-Requested-With, Content-Type, Accept,X-Custom-Header");
		response.setHeader("X-Powered-By", "SpringBoot");
		if ("option".equalsIgnoreCase(request.getMethod())) {
			responseJSON(response, new HashMap<>());
			return;
		}
		//ajax请求不跳转，因为没法跳转
		String xReq = request.getHeader("x-requested-with");
		Boolean isAjax = false;
		if (StringUtils.isNotBlank(xReq) && "XMLHttpRequest".equalsIgnoreCase(xReq)) {
			isAjax = true;
		}
		//除了拦截login.html 其他html都拦截
		StringBuffer url = request.getRequestURL();
		//System.out.println(url);
		String path = url.toString();
//		User user1 = userService.checkLogin("admin", "admin");
//		request.getSession().setAttribute("user", user1);
//		User user2 = userService.checkManagerLogin("admin", "admin");
//		request.getSession().setAttribute("manager_user", user2);
		// 只拦截这些类型请求
		if (needFilter(path) && !isAjax) {
			//此处为了post验证暂不开启登陆验证
			//			chain.doFilter(request, response);
			processAccessControl(request, response, chain);
		} else {
			//其他静态资源都不拦截
			chain.doFilter(request, response);
		}
	}

	/**
	 * 判断所有需要filter的页面
	 * @param path
	 * @return
	 */
	private boolean needFilter(String path) {
		//所有登陆登出，注册与错误页不过滤
		if (path.contains("login") || path.contains("logout") || path.contains("register") || path.contains("error")) {
			return false;
			//所有管理页都要已登陆状态，包含查询与展示页面
		} else if (path.contains("manager/product/img")) {
			return false;
		} else if (path.contains("/order/submit")) {
			return false;
		} else if (path.contains("manager") || path.contains("order")) {
			return true;
		}
		return false;
	}


	/*{
		// 登录，图片不拦截
		if (path.endsWith("toLogin.html")
				|| path.endsWith("toRegister.html")
				|| path.endsWith("register.do")
				|| path.endsWith("login.do")
				|| path.endsWith("logout.do")
				|| path.endsWith("error.html")
				|| path.endsWith("checkUsername.do")
				|| path.indexOf("/mall/admin/product/img/") != -1
				|| path.endsWith("index")
				|| path.endsWith("classification/list.do")
				|| path.indexOf("product") != -1) {
			chain.doFilter(request, response);
		} else*/

	/**
	 * @param request
	 * @param response
	 * @param chain
	 * @throws IOException
	 * @throws ServletException
	 */
	private void processAccessControl(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		Object managerUser = request.getSession().getAttribute("manager_user");
		Object user = request.getSession().getAttribute("user");
		String url = request.getRequestURL().toString();
		//所有后端管理页被拦截都跳转到后端登陆页
		if (url.contains("manager")) {
			if (managerUser == null) {
				response.sendRedirect("/fleastreet/manager/login");
			} else {
				chain.doFilter(request, response);
			}
		} else {
			//所有前端部分页面被拦截都跳转到前端登陆页，比如订单页
			if (user == null) {
				response.sendRedirect("/fleastreet/user/login");
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	@Override
	public void destroy() {

	}

	/**
	 * 返回JOSN数据格式
	 *
	 * @param response
	 * @param object
	 * @throws IOException
	 */
	public static void responseJSON(HttpServletResponse response, Object object) throws IOException {
		response.setContentType("application/json;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		ObjectMapper mapper = new ObjectMapper();
		if (object == null)
			return;
		String jsonStr = mapper.writeValueAsString(object);
		OutputStream out = response.getOutputStream();
		out.write(jsonStr.getBytes("UTF-8"));
		out.flush();
	}

}
